import React, {useEffect, useState} from 'react'
import {Form, Button, DatePicker, Input, Modal, Radio, Select, Row, Col, message, Upload, Descriptions } from 'antd'
import {UploadOutlined} from '@ant-design/icons';
import {dimissionTypeList, modeList, evaluationList, resignationTemplateURL} from '@/utils/constant'
import {connect} from 'umi'
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment'
import "../style.less";
import SelectUserModal from "@/pages/components/SelectUserModal";
import { SearchOutlined } from '@ant-design/icons';

const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;
const { Search } = Input;
const RadioGroup = Radio.Group;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const {visible, onSubmit, current, onCancel, currentUser = {}, personnel = {}} = props;
  const {options = {}} = personnel;
  const {orgTree = [], jobLevel = []} = options;
  const [form] = Form.useForm();
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [userInfo, setUserInfo] = useState(null);
  const [currentUserInfo, setCurrentUserInfo] = useState(null);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          form.setFieldsValue({fileUploadUrls: urls});
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
      form.setFieldsValue({fileUploadUrls: urls});
    }
  };

  useEffect(() => {
    if (visible){
      if (current){
        setUserInfo({name: current.name,oid:current.oid,applyOid:current.oid});
        if (current.urlIds){
          let fileUrlList = current.urlIds.split(',');
          setFileUploadUrls(fileUrlList);
          fileUrlList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          })
        }
        current.applyTime = current.applyTime && moment(current.applyTime);
        current.dimissionTime = current.dimissionTime && moment(current.dimissionTime);
        current.hiredate = current.hiredate && moment(current.hiredate);
        current.jobLevel = jobLevel.find(item => (item.id === current.jobLevelId))?.name;
        form.setFieldsValue(current);
      }else {
        let data = {
          applyOid: currentUser.id,
          applyCode: currentUser.usercode,
          applyDepartment: currentUser.department,
          applyName: currentUser.name,
          applyTime: moment()
        };
        setCurrentUserInfo(data);
        form.setFieldsValue(data);
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    setFileUploadUrls([]);
    uploadedFiles = [];
    setUserInfo(null);
    form.resetFields();
    onCancel();
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    let id = current ? current.id : null;
    onSubmit({...userInfo, ...fieldsValue, ...currentUserInfo, urlIdsList: fileUploadUrls, id});
    setUserInfo(null);
    setFileUploadUrls([]);
    uploadedFiles = [];
    form.resetFields();
  };

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  };

  const showSelectUserModal = () => {
    setUserModalVisible(true);
  };

  const confirmSelectUser = (info) => {
    if (info) {
      let workingStartTimeDate = moment(info[0].hiredate);
      let workingEndDate = moment();
      let needsUserInfo = {
        oid: info[0].oid,
        code: info[0].code,
        name: info[0].name,
        hiredate: moment(info[0].hiredate),
        workingYears: info[0].hiredate ? `${workingEndDate.diff(workingStartTimeDate, 'years',true).toFixed(1)}年` : '',
        unitname: info[0].unitname,
        unitId: info[0].unitId,
        orgname: info[0].orgname,
        orgId: info[0].orgId,
        jobname: info[0].jobname,
        jobId: info[0].jobId,
        jobLevelType: info[0].jobLevelType,
        jobLevelId: info[0].jobLevelId,
        jobLevel: jobLevel.find(item => (item.id === info[0].jobLevelId))?.name,
        line: info[0].line,
        lineId: info[0].lineId,
        jobSystem: info[0].jobSystem,
        jobSystemId: info[0].jobSystemId,
      };
      const fieldsValue = form.getFieldsValue();
      setUserInfo({...needsUserInfo});
      form.setFieldsValue({...fieldsValue, ...needsUserInfo});
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const downloadTemplate = () => {
    window.open(resignationTemplateURL)
  };

  const renderContent = () => {
    return (<>
      <Row gutter={24}>
        <Col {...colStyle}>
          <FormItem name="applyName" label="申请人">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="applyTime" label="申请日期">
            <DatePicker disabled={true} className='widthStyle'/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="code" label="工号" >
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="name" label="姓名" rules={[{required: true, message: '请选择离职员工'}]}>
            <Input.Group compact size="large">
              <Input style={{ width: '80%',height: '32px', fontSize:'14px', background: '#ffffff' }} placeholder="选择离职员工" value={userInfo ? userInfo.name : ''} disabled={true}/>
              <Button style={{ width: '20%' }} icon={<SearchOutlined/>} onClick={() => showSelectUserModal()} />
            </Input.Group>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="orgname" label="公司名称">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="unitname" label="部门名称">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="jobname" label="岗位">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="jobLevel" label="职级">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="hiredate" label="入职日期">
            <DatePicker disabled={true} className='widthStyle'/>
          </FormItem>
        </Col>

        <Col {...colStyle}>
          <FormItem name="workingYears" label="司龄">
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="dimissionTime" label="离职日期" rules={[{required: true, message: '请选择离职日期'}]}>
            <DatePicker className='widthStyle'/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <Form.Item name="mode" label="离职方式" rules={[{required: true, message: '请选择离职方式'}]}>
            <Select placeholder="请选择" showSearch filterOption={filterOption}>
              {modeList.map((item, index) => {
                return (
                  <Option value={`${item.value}`} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
        </Col>
        <Col {...colStyle}>
          <Form.Item name="dimissionType" label="离职类型" rules={[{required: true, message: '请选择离职类型'}]}>
            <Select placeholder="请选择" showSearch filterOption={filterOption}>
              {dimissionTypeList.map((item, index) => {
                return (
                  <Option value={`${item.value}`} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
        </Col>
        <Col {...colStyle}>
          <FormItem name="associate" label="工作接收人" rules={[{required: true, message: '请填工作接收人'}]}>
            <Input/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
            <FormItem label="附件上传" name="fileUploadUrls" labelCol={{span:7}} wrapperCol={{span:17}} rules={[{required: true, message: '请上传离职申请书'}]}>
              <div style={{display:'flex'}}>
                <Upload {...fileProps} className='uploadWidth'>
                  <Button>
                    <UploadOutlined/> 点击上传附件
                  </Button>
                </Upload>
                <a href={resignationTemplateURL} style={{height:'32px',lineHeight:'32px',marginLeft:'10px'}}>模板下载</a>
              </div>
            </FormItem>
        </Col>
        <Row className='textCenter' gutter={24}>
          <Col className='padding backGroundColor' span={10}>项目</Col>
          <Col className='padding backGroundColor' span={14}>评价</Col>

          <Col span={10} className='alignCenter padding' >主管辅导</Col>
          <Col span={14} className='alignCenter padding' >
            <FormItem name="spervisorCoaching" rules={[{required: true, message: '请选择主管辅导评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>

          <Col span={10} className='alignCenter padding' >薪资报酬</Col>
          <Col span={14} className='alignCenter padding' >
            <FormItem name="slaryCompensation" rules={[{required: true, message: '请选择薪资报酬评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>

          <Col span={10} className='alignCenter padding'>工作时间</Col>
          <Col span={14} className='alignCenter padding'>
            <FormItem name="operatingHours" rules={[{required: true, message: '请选择工作时间评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>

          <Col span={10} className='alignCenter padding'>培训获得</Col>
          <Col span={14} className='alignCenter padding'>
            <FormItem name="trainingObtained" rules={[{required: true, message: '请选择培训获得评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>

          <Col span={10} className='alignCenter padding'>升迁机会</Col>
          <Col span={14} className='alignCenter padding'>
            <FormItem name="promotionOpportunity" rules={[{required: true, message: '请选择升迁机会评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>

          <Col span={10} className='alignCenter padding'>沟通渠道</Col>
          <Col span={14} className='alignCenter padding'>
            <FormItem name="communicationChannel" rules={[{required: true, message: '请选择沟通渠道评价'}]}>
              <RadioGroup>
                {evaluationList.map((item, index) => (<Radio key={index} value={item.value}>{item.label}</Radio>))}
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>
        <Col span={24} style={{marginTop:10}}>
          <FormItem name="reason" labelCol={{span: 2}} label="离职原因">
            <TextArea rows={8} className='widthStyle'/>
          </FormItem>
        </Col>
        <Col span={24}>

        </Col>
      </Row>
    </>)
  };

  const renderFooter = () => (
    <>
      <Button onClick={() => onFormCancel()}>取消</Button>
      <Button type="primary" onClick={() => handleNext()}>
        完成
      </Button>
    </>
  );

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="新建"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>

      <SelectUserModal
        selectType={0}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
        isOrgGroupFilter={true}
      />
    </Modal>
  )
};

export default connect(({user, personnel, global}) => ({
  personnel,
  global,
  currentUser: user.currentUser,
}))(CreateForm)
